package com.example.erp;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.mcp.SyncMcpToolCallbackProvider;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import io.modelcontextprotocol.client.McpSyncClient;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import reactor.core.publisher.Flux;

/**
 * 采用自定义mcp服务，基于 openai 通过 llm 访问，实现一个天气管理服务。<br>
 * <p>
 * chatopenai前置条件：<br/>
 * 1、application.properties 配置 weather 指定 mcp-servers-config.json ;<br/>
 * 
 * chatopenai2前置条件：<br/>
 * 1、在 clientConfig.java 中注入 weather 配置信息<br/>
 * @author jiang 2025-03-20
 */

@RestController
public class ChatController {

	@Resource
	private OpenAiChatModel openAiChatModel;
	// 必须配置：spring.ai.mcp.client.toolcallback.enabled=true，否则 Spring 不会自动创建 SyncMcpToolCallbackProvider Bean。
	@Resource
	private SyncMcpToolCallbackProvider toolCallbackProviders; 
	
	@Resource
	private ChatClient.Builder chatClientBuilder;
	@Resource
	private McpSyncClient mcpClient;

//	http://localhost:8081/mcp/chat?input=北京今天天气如何？
	@GetMapping("/chat")
	public Flux<String> openaicall(@RequestParam String input, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		// 注入的 OpenAiChatModel 默认配置参数[defaultOptions=OpenAiChatOptions: {"streamUsage":false,"model":"deepseek-chat","temperature":0.7}]
		ChatClient chatClient = ChatClient.builder(openAiChatModel)				
				// toolCallbackProviders 包含 mcp-servers-config.json 中配置的所有服务
				.defaultTools(toolCallbackProviders)
				.build();	
		
		// 流式返回
		return chatClient.prompt(input).stream().content();
	}
	
//	http://localhost:8081/mcp/chat2?input=上海今天天气如何?
	@GetMapping("/chat2")
	public Flux<String> openaicall2(@RequestParam String input, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");

		ChatClient chatClient = chatClientBuilder
				// ClientConfig.java 中配置的 mcpClient bean 中包含的服务
				.defaultTools(new SyncMcpToolCallbackProvider(mcpClient))
				.build();
		
		// 流式返回
		return chatClient.prompt(input).stream().content();
	}
}